package com.qubuyer.business.mine.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import com.qubuyer.R
import com.qubuyer.business.mine.viewmodel.UserViewModel
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.databinding.FragmentUpdateNicknameBinding

/**
 * @author Susong
 * @date 创建时间2019/4/12
 * @description 修改昵称activity
 * @version
 */
class UpdateNickNameFragment : MVVMFragment<FragmentUpdateNicknameBinding, UserViewModel>() {

    override fun onDataBinding(dataBinding: FragmentUpdateNicknameBinding) {
        dataBinding.host = this
    }

    override val viewModel: UserViewModel by injectVMByActivity()
    override val layoutId: Int
        get() = R.layout.fragment_update_nickname

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewDataBinding.etNickname.doAfterTextChanged {
            viewDataBinding.ivDelete.isVisible = !it.isNullOrEmpty()
        }
        viewModel.userEntity.observe(viewLifecycleOwner, {
            viewDataBinding.etNickname.setText(it.nickname)
            viewDataBinding.etNickname.setSelection(viewDataBinding.etNickname.text.length)
        })
    }

    override fun getTitle(): String {
        return "昵称"
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.iv_delete -> viewDataBinding.etNickname.setText("")
            R.id.tv_save -> {
                val nickname = viewDataBinding.etNickname.text.toString()
                if (TextUtils.isEmpty(nickname)) {
                    toast("请输入昵称")
                    return
                }
                viewModel.userInfoEdit(nickname) {
                    toast("修改用户昵称成功")
                    mContext.onBackPressed()
                }
            }
        }
    }
}